package ei

import (
	"io/ioutil"
	"strings"
)

func ReadCSV(str string) [][]Token {
	var file [][]Token
	str = strings.ReplaceAll(str, "\r", "\n")
	str = strings.ReplaceAll(str, "\n\n", "\n")
	spited := strings.Split(str, "\n")
	for _, s := range spited{
		t := char2Token([]rune(s), defFixSymbol)
		t = ExplainSymbol(t)
		t = createList(t)
		file = append(file, t)
	}
	return file
}

func ReadCSVFile(filePath string, varAddr *Token) {
	b, err := ioutil.ReadFile(filePath)
	if err != nil {
		panic(err)
	} else {
		v := ReadCSV(string(b))
		list := make([]Token, len(v))
		for i := 0; i < len(v); i++ {
			list[i] = Token{
				TypeClass: TYPE_LIST,
				Value:     v[i],
			}
		}
		*varAddr = Token{
			TypeClass: TYPE_LIST,
			Value:     list,
		}
	}
}

func SaveCSV(v [][]Token) string {
	var fileStr string
	for _, line := range v{
		for _, item := range line {
			fileStr += GetString(item) + ","
		}
		fileStr += "\n"
	}
	return fileStr
}

func SaveCSVFile(v [][]Token, filePath string)  {
	err :=ioutil.WriteFile(filePath, []byte(SaveCSV(v)), 0666)
	if err != nil {
		panic(err)
	}
}

func SaveCSVFromToken(v Token) string {
	var fileStr string
	if v.TypeClass != TYPE_LIST {
		panic("写入CSV的Token不是数组")
	}
	lines := v.Value.([]Token)
	for _, line := range lines{
		if line.TypeClass == TYPE_LIST {
			for _, item := range line.Value.([]Token) {
				fileStr += GetString(item) + ","
			}
		} else {
			fileStr += GetString(line)
		}
		fileStr += "\n"
	}
	return fileStr
}

func SaveCSVFileFromToken(v Token, filePath string) {
	err := ioutil.WriteFile(filePath, []byte(SaveCSVFromToken(v)), 0666)
	if err != nil {
		panic(err)
	}
}